/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.boot.util;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import com.iwindplus.boot.domain.constant.CommonConstant;
import com.iwindplus.boot.util.domain.dto.ProtostuffDTO;
import lombok.extern.slf4j.Slf4j;

/**
 * Protostuff工具类.
 *
 * @author zengdegui
 * @since 2018/9/1
 */
@Slf4j
public class ProtostuffUtil {

    private ProtostuffUtil() {
        throw new IllegalStateException(CommonConstant.UTILITY_CLASS);
    }

    /**
     * 避免每次序列化都重新申请Buffer空间.
     */
    private static final LinkedBuffer BUFFER = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);

    /**
     * 缓存Schema.
     */
    private static final Schema<ProtostuffDTO> SCHEMA = RuntimeSchema.getSchema(ProtostuffDTO.class);

    /**
     * 序列化为字节数组.
     *
     * @param obj 对象
     * @param <T> 泛型
     * @return byte[]
     */
    public static <T> byte[] toJsonBytes(T obj) {
        final ProtostuffDTO data = ProtostuffDTO.builder()
            .data(obj)
            .build();
        try {
            return ProtostuffIOUtil.toByteArray(data, SCHEMA, BUFFER);
        } finally {
            BUFFER.clear();
        }
    }

    /**
     * 序列化为字节数组.
     *
     * @param bytes 字节数组
     * @param <T>   泛型
     * @return T
     */
    public static <T> T parseBytes(byte[] bytes) {
        final ProtostuffDTO protostuff = SCHEMA.newMessage();
        try {
            ProtostuffIOUtil.mergeFrom(bytes, protostuff, SCHEMA);
            return (T) protostuff.getData();
        } finally {
            BUFFER.clear();
        }
    }

}
